import os
import requests
import json


def getAccess_token():
    # 获取appkey
    appkey = "ding5okq0au7cvmiokap"
    appsecret = "z2Fa0QVgXg5yFLaAbWYVNC_oCsZyKZQS9j845xN8NBOc5egJwr25ByHJfvKdD5y-"
    url = 'https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s' % (appkey, appsecret)
    print(url)
    headers = {
        'Content-Type': "application/x-www-form-urlencoded"
    }
    data = {'appkey': appkey,
            'appsecret': appsecret}
    r = requests.request('GET', url, data=data, headers=headers)
    access_token = r.json()["access_token"]
    return access_token


def getMedia_id():
    access_token = getAccess_token()
    # 获取要发送的文件
    path = r"D:\pycharm\project\marketing-system\data\接口用例.xls"
    url = r'https://oapi.dingtalk.com/media/upload?access_token=%s&type=file' % access_token
    print(path)
    files = {'media': open(path, 'rb')}
    data = {'access_token': access_token,
            'type': 'file'}
    response = requests.post(url, files=files, data=data)
    json = response.json()
    print(json)
    return json["media_id"]


def SendFile():
    access_token = getAccess_token()
    media_id = getMedia_id()
    # 获取chatid
    chatid = 'chatb7d8bb2908f6639d6c16d1984d223295'  # 通过jsapi工具获取的群聊id
    url = 'https://oapi.dingtalk.com/chat/send?access_token=' + access_token
    print(url)
    header = {
        'Content-Type': 'application/json'
    }
    data = {'access_token': access_token,
            'chatid': chatid,
            'msg': {
                'msgtype': 'file',
                'file': {'media_id': media_id
                         }
            }
            }
    print(data)
    r = requests.request('POST', url, json=data, headers=header)
    print(r.json())


if __name__ == "__main__":
    SendFile()
